<?php
session_start();
ini_set('disable_functions', 'exec,system,passthru,shell_exec,proc_open,popen,curl_exec,parse_ini_file,show_source,file_get_contents,fopen,file_put_contents,unlink,rmdir,rename,copy,chmod');
// 定义函数：检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true); // 创建目录
        }
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

// 当前用户
$currentUser = $_SESSION['username'] ?? null;
$targetUserId = $_GET['id'] ?? null;

// 验证登录状态
if (!$currentUser) {
    die(json_encode(['status' => 'error', 'message' => '用户未登录！']));
}

if (!$targetUserId) {
    die(json_encode(['status' => 'error', 'message' => '未指定聊天用户！']));
}
require_once 'track_online.php';
// 加载好友关系文件
$friendFile = __DIR__ . '/ffile.json';
$friendConfig = ensureFile($friendFile);
$friendFile = __DIR__ . '/ffile.json';
$friendConfig = ensureFile($friendFile);

// 检查是否还是好友
$isFriend = isset($friendConfig[$currentUser]) && in_array($targetUserId, $friendConfig[$currentUser]);
$isFriendOf = isset($friendConfig[$targetUserId]) && in_array($currentUser, $friendConfig[$targetUserId]);

// 如果双方都不是好友（即已被删除）
// ...（前面的代码保持不变）...

// 如果双方都不是好友（即已被删除）
if (!$isFriend && !$isFriendOf) {
    ?>
    <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>关系结束 - JIIL微聊</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background: #f8fafc;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            max-width: 500px;
            width: 100%;
        }
        
        .error-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            text-align: center;
            padding: 50px 30px;
            position: relative;
        }
        
        .error-icon {
            position: relative;
            width: 100px;
            height: 100px;
            margin: 0 auto 30px;
        }
        
        .exclamation-circle {
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background: #ff6b6b;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .exclamation-mark {
            position: relative;
            width: 16px;
            height: 50px;
            background: white;
            border-radius: 8px;
        }
        
        .exclamation-mark::after {
            content: '';
            position: absolute;
            bottom: -20px;
            left: 50%;
            transform: translateX(-50%);
            width: 16px;
            height: 16px;
            background: white;
            border-radius: 50%;
        }
        
        .error-title {
            font-size: 26px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 15px;
            letter-spacing: 0.5px;
        }
        
        .error-subtitle {
            font-size: 18px;
            color: #e53e3e;
            font-weight: 500;
            margin-bottom: 25px;
        }
        
        .error-message {
            font-size: 16px;
            color: #718096;
            line-height: 1.7;
            max-width: 400px;
            margin: 0 auto 30px;
        }
        
        .error-detail {
            font-size: 14px;
            color: #a0aec0;
            margin-top: 25px;
            padding-top: 25px;
            border-top: 1px solid #edf2f7;
        }
        
        .btn-container {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 30px;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 12px 28px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: none;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background: #2980b9;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #e74c3c;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #c0392b;
            transform: translateY(-2px);
        }
        
        .btn-outline {
            background: transparent;
            color: #718096;
            border: 1px solid #e2e8f0;
        }
        
        .btn-outline:hover {
            background: #f8fafc;
        }
        
        .btn i {
            margin-right: 8px;
        }
        
        @media (max-width: 576px) {
            .error-card {
                padding: 40px 20px;
            }
            
            .error-title {
                font-size: 22px;
            }
            
            .error-subtitle {
                font-size: 16px;
            }
            
            .error-message {
                font-size: 14px;
            }
            
            .btn {
                padding: 10px 20px;
                font-size: 14px;
                width: 100%;
                margin-bottom: 10px;
            }
            
            .btn-container {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="error-card">
            <div class="error-icon">
                <div class="exclamation-circle">
                    <div class="exclamation-mark"></div>
                </div>
            </div>
            
            <h1 class="error-title">你们的关系渐行渐远</h1>
            <div class="error-subtitle">对方已不是你的好友</div>
            <div class="error-subtitle">你可以选择留着好友记录或者  删除</div>
            
            
            <div class="btn-container">
                <a href="index.php" class="btn btn-primary">
                    <i class="fas fa-home"></i> 返回主页
                </a>
                <a href="remove_friend_record.php?id=<?= urlencode($targetUserId) ?>" class="btn btn-secondary">
        <i class="fas fa-trash-alt"></i> 删除好友记录
    </a>
            </div>
        </div>
    </div>
</body>
</html>
    <?php
    exit();
}

// ...（后面的代码保持不变）...
// 验证好友关系
if (!isset($friendConfig[$currentUser]) || !in_array($targetUserId, $friendConfig[$currentUser])) {
    die(json_encode(['status' => 'error', 'message' => "你没有权限与 $targetUserId 聊天！"]));
}

// 定义共享聊天文件路径
$sharedChatFile = __DIR__ . "/messages/shared_chats/{$currentUser}_{$targetUserId}.json";
if ($currentUser > $targetUserId) {
    $sharedChatFile = __DIR__ . "/messages/shared_chats/{$targetUserId}_{$currentUser}.json";
}
ensureFile($sharedChatFile);

// 消息处理：获取消息
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['fetch_messages'])) {
    $messages = json_decode(file_get_contents($sharedChatFile), true);
    echo json_encode($messages);
    exit();
}

// 消息处理：发送文本消息
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $message = trim($_POST['message']);

    if (empty($message)) {
        echo json_encode(['status' => 'error', 'message' => '消息不能为空']);
        exit();
    }

    if (mb_strlen($message, 'UTF-8') > 1000) {
        echo json_encode(['status' => 'error', 'message' => '消息长度不能超过 1000 字']);
        exit();
    }

    // 读取现有消息
    $messages = json_decode(file_get_contents($sharedChatFile), true);

    // 添加新消息
    $newMessage = [
        'sender' => $currentUser,
        'content' => htmlspecialchars($message),
        'type' => 'text',
        'timestamp' => date('Y-m-d H:i:s')
    ];

    $messages[] = $newMessage;

    // 保存到聊天文件
    file_put_contents($sharedChatFile, json_encode($messages));

    echo json_encode(['status' => 'success', 'message' => '消息已发送']);
    exit();
}

// 消息处理：发送图片
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
        // 确定上传目录
        $uploadsDir = __DIR__ . "/uploads";
        if (!is_dir($uploadsDir)) {
            mkdir($uploadsDir, 0777, true);
        }

        // 生成唯一文件名保存图片
        $imagePath = $uploadsDir . "/" . uniqid() . "_" . basename($_FILES['image']['name']);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
            // 获取相对路径以供前端使用
            $relativeImagePath = str_replace(__DIR__, '', $imagePath);

            $newMessage = [
                'sender' => $currentUser,
                'content' => $relativeImagePath, // 存储相对路径
                'type' => 'image',
                'timestamp' => date('Y-m-d H:i:s')
            ];

            $messages = json_decode(file_get_contents($sharedChatFile), true);
            $messages[] = $newMessage;
            file_put_contents($sharedChatFile, json_encode($messages));

            echo json_encode(['status' => 'success', 'message' => '图片已发送']);
            exit();
        }
    }

    echo json_encode(['status' => 'error', 'message' => '图片上传失败']);
    exit();
}
// 在加载好友关系文件后添加

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>与 <?= htmlspecialchars($targetUserId) ?> 的聊天</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        /* 顶部导航栏 */
        .navbar {
            background-color: #ffffff;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            position: relative;
            z-index: 100;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000000;
            font-size: 20px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #e4f1ff;
        }
        
        .user-details {
            display: flex;
            flex-direction: column;
        }
        
        .username {
            font-weight: 600;
            font-size: 16px;
            color: #2d3748;
        }
        
        .menu-btn {
            background: none;
            border: none;
            color: #718096;
            font-size: 20px;
            margin-left: auto;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .menu-btn:hover {
            background: #f0f4f8;
        }
        
        .dropdown-menu {
            position: absolute;
            top: 60px;
            right: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            padding: 10px 0;
            width: 180px;
            z-index: 1000;
            display: none;
        }
        
        .dropdown-menu.show {
            display: block;
        }
        
        .menu-item {
            padding: 12px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            color: #4a5568;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .menu-item:hover {
            background: #f8fafc;
            color: #3498db;
        }
        
        .menu-item i {
            width: 20px;
            text-align: center;
        }
        
        .menu-item.delete {
            color: #e53e3e;
        }
        
        .menu-item.delete:hover {
            background: #fff5f5;
        }
        
        /* 聊天区域 */
        .chat-container {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
            scroll-behavior: smooth;
            position: relative;
        }
        
        .message {
            max-width: 75%;
            padding: 12px 16px;
            border-radius: 18px;
            font-size: 15px;
            line-height: 1.5;
            position: relative;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message.received {
            background: #f0f4f8;
            align-self: flex-start;
            border-bottom-left-radius: 4px;
        }
        
        .message.sent {
            background: #3498db;
            color: white;
            align-self: flex-end;
            border-bottom-right-radius: 4px;
        }
        
        .message.sending {
            opacity: 0.7;
        }
        
        .message.failed {
            background: #fff0f0;
            border: 1px solid #fed7d7;
        }
        
        .message img {
            max-width: 100%;
            border-radius: 10px;
            cursor: pointer;
            display: block;
        }
        
        .message-time {
            font-size: 11px;
            color: #a0aec0;
            margin-top: 5px;
            text-align: right;
        }
        
        .message.sent .message-time {
            color: rgba(255,255,255,0.7);
        }
        
        .message-status {
            position: absolute;
            bottom: 8px;
            right: 12px;
            font-size: 12px;
        }
        
        .message.sending .message-status {
            color: #a0aec0;
        }
        
        .message.failed .message-status {
            color: #e53e3e;
        }
        
        /* 输入区域 */
        .input-container {
            background-color: #ffffff;
            border-top: 1px solid #e2e8f0;
            padding: 15px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .message-input {
            flex: 1;
            resize: none;
            height: 50px;
            border: 1px solid #e2e8f0;
            border-radius: 25px;
            padding: 14px 20px;
            font-size: 15px;
            transition: all 0.3s ease;
            background: #f8fafc;
        }
        
        .message-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .action-btn {
            background: none;
            border: none;
            color: #718096;
            font-size: 22px;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            background: #f0f4f8;
            color: #3498db;
        }
        
        .send-btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 50%;
            width: 44px;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .send-btn:hover {
            background: #2980b9;
            transform: scale(1.05);
        }
        
        .emoji-panel {
            position: absolute;
            bottom: 80px;
            left: 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.1);
            padding: 15px;
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 8px;
            z-index: 100;
            display: none;
        }
        
        .emoji-panel.show {
            display: grid;
        }
        
        .emoji-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }
        
        .emoji-btn:hover {
            background: #f0f4f8;
            transform: scale(1.2);
        }
        
        #file-input {
            display: none;
        }
        
        .image-preview {
            max-width: 200px;
            border-radius: 10px;
            margin-top: 10px;
            display: none;
        }
        
        .image-preview.show {
            display: block;
        }
        
        /* 图片预览 */
        .image-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        
        .image-overlay.show {
            opacity: 1;
            pointer-events: all;
        }
        
        .image-overlay img {
            max-width: 90%;
            max-height: 90%;
            border-radius: 10px;
        }
        
        .close-preview {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }
        
        /* 加载指示器 */
        .loader {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 滚动到底部按钮 */
        .scroll-to-bottom {
            position: fixed;
            bottom: 100px;
            right: 20px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #3498db;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
            z-index: 500;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s ease;
        }
        
        .scroll-to-bottom.visible {
            opacity: 1;
            transform: translateY(0);
        }
        
        .scroll-to-bottom:hover {
            background: #2980b9;
            transform: translateY(-2px) scale(1.05);
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .message {
                max-width: 85%;
            }
            
            .input-container {
                padding: 10px;
            }
            
            .message-input {
                height: 45px;
                padding: 12px 18px;
            }
            
            .scroll-to-bottom {
                bottom: 90px;
                right: 15px;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="navbar">
        <button class="back-btn" onclick="location.href='index.php'">
            <i class="fas fa-arrow-left"></i>
        </button>
        
        <div class="user-details">
            <div class="username"><?= htmlspecialchars($targetUserId) ?></div>
        </div>
        
        <button class="menu-btn" onclick="toggleMenu()">
            <i class="fas fa-ellipsis-v"></i>
        </button>
        
        <div class="dropdown-menu">
            <div class="menu-item" onclick="ckfr()">
                <i class="fas fa-user"></i>
                <span>查看资料</span>
            </div>
            <div class="menu-item" onclick="location.href='ewm.php?user=<?= htmlspecialchars($targetUserId) ?>'">
                <i class="fas fa-share-alt"></i>
                <span>分享好友</span>
            </div>
            <!-- 在现有的菜单项下方添加 -->
<div class="menu-item delete" onclick="deleteFriend()">
    <i class="fas fa-user-minus"></i>
    <span>删除好友</span>
</div>

        </div>
    </div>
    
    <!-- 聊天区域 -->
    <div class="chat-container" id="chatContainer"></div>
    
    <!-- 滚动到底部按钮 -->
    <div class="scroll-to-bottom" id="scrollToBottomBtn">
        <i class="fas fa-arrow-down"></i>
    </div>
    
    <!-- 输入区域 -->
    <div class="input-container">

        
        <textarea class="message-input" name="message" placeholder="输入消息..."></textarea>
        
        <!-- 图片上传按钮（使用相机图标） -->
        <button class="action-btn" onclick="triggerFileInput()">
            <i class="fas fa-camera"></i>
        </button>
         <button class="action-btn" onclick="toggleEmojiPanel()">
            <i class="far fa-smile"></i>
        </button>
        
        <button class="send-btn" onclick="sendMessage(event)">
            <i class="fas fa-paper-plane"></i>
        </button>
        
        <input type="file" id="file-input" accept="image/*" onchange="uploadImage(event)">
    </div>
    
    <!-- 表情面板 -->
    <!-- 表情面板 -->
<div class="emoji-panel" id="emojiPanel">
    <button class="emoji-btn" onclick="addEmoji('😊')">😊</button>
    <button class="emoji-btn" onclick="addEmoji('😂')">😂</button>
    <button class="emoji-btn" onclick="addEmoji('❤️')">❤️</button>
    <button class="emoji-btn" onclick="addEmoji('👍')">👍</button>
    <button class="emoji-btn" onclick="addEmoji('🎉')">🎉</button>
    <button class="emoji-btn" onclick="addEmoji('😍')">😍</button>
    <button class="emoji-btn" onclick="addEmoji('🙏')">🙏</button>
    <button class="emoji-btn" onclick="addEmoji('👏')">👏</button>
    <button class="emoji-btn" onclick="addEmoji('😎')">😎</button>
    <button class="emoji-btn" onclick="addEmoji('🤔')">🤔</button>
    <button class="emoji-btn" onclick="addEmoji('🥳')">🥳</button>
    <button class="emoji-btn" onclick="addEmoji('🤩')">🤩</button>
    
    <!-- 新增表情 -->
    <button class="emoji-btn" onclick="addEmoji('😘')">😘</button>
    <button class="emoji-btn" onclick="addEmoji('😜')">😜</button>
    <button class="emoji-btn" onclick="addEmoji('🤪')">🤪</button>
    <button class="emoji-btn" onclick="addEmoji('🥰')">🥰</button>
    <button class="emoji-btn" onclick="addEmoji('🤗')">🤗</button>
    <button class="emoji-btn" onclick="addEmoji('🤭')">🤭</button>
    <button class="emoji-btn" onclick="addEmoji('🤫')">🤫</button>
    <button class="emoji-btn" onclick="addEmoji('🤐')">🤐</button>
    <button class="emoji-btn" onclick="addEmoji('🤨')">🤨</button>
    <button class="emoji-btn" onclick="addEmoji('😐')">😐</button>
    <button class="emoji-btn" onclick="addEmoji('😑')">😑</button>
    <button class="emoji-btn" onclick="addEmoji('😶')">😶</button>
    <button class="emoji-btn" onclick="addEmoji('😏')">😏</button>
    <button class="emoji-btn" onclick="addEmoji('😒')">😒</button>
    <button class="emoji-btn" onclick="addEmoji('🙄')">🙄</button>
    <button class="emoji-btn" onclick="addEmoji('😬')">😬</button>
    <button class="emoji-btn" onclick="addEmoji('🤥')">🤥</button>
    <button class="emoji-btn" onclick="addEmoji('😌')">😌</button>
    <button class="emoji-btn" onclick="addEmoji('😔')">😔</button>
</div>
    
    <!-- 图片预览 -->
    <div class="image-overlay" id="imageOverlay">
        <i class="fas fa-times close-preview" onclick="closePreview()"></i>
        <img id="previewImage" src="" alt="预览图片">
    </div>
    
    <script>
        // 全局变量
        let lastMessageId = 0;
        let pendingMessages = {};
        let isAtBottom = true;
        const targetUserId = "<?= htmlspecialchars($targetUserId) ?>";
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化聊天
            refreshMessages();
            
            // 设置定时刷新新消息
            setInterval(fetchNewMessages, 2000);
            
            // 监听输入框回车发送
            document.querySelector('.message-input').addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage(e);
                }
            });
            
            // 监听滚动事件
            const chatContainer = document.getElementById('chatContainer');
            chatContainer.addEventListener('scroll', handleScroll);
            
            // 滚动到底部按钮点击事件
            document.getElementById('scrollToBottomBtn').addEventListener('click', scrollToBottom);
        });
        
        // 处理滚动事件
        function handleScroll() {
            const chatContainer = document.getElementById('chatContainer');
            const scrollBtn = document.getElementById('scrollToBottomBtn');
            
            // 计算是否在底部（允许5px的误差）
            isAtBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight <= 5;
            
            // 显示/隐藏滚动到底部按钮
            if (isAtBottom) {
                scrollBtn.classList.remove('visible');
            } else {
                scrollBtn.classList.add('visible');
            }
        }
        
        // 滚动到底部
        function scrollToBottom() {
            const chatContainer = document.getElementById('chatContainer');
            chatContainer.scrollTop = chatContainer.scrollHeight;
            document.getElementById('scrollToBottomBtn').classList.remove('visible');
            isAtBottom = true;
        }
        
        // 显示/隐藏菜单
        function toggleMenu() {
            const menu = document.querySelector('.dropdown-menu');
            menu.classList.toggle('show');
        }
        
        // 删除好友
     function deleteFriend() {
        if (!confirm('确定要删除好友吗？此操作不可撤销！')) {
            return;
        }
        
        // 使用全局变量 targetUserId
        const formData = new FormData();
        formData.append('delete_friend', 'true');
        formData.append('id', targetUserId);
        
        fetch('chat.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                alert(result.message);
                window.location.href = 'index.php';
            } else {
                alert(result.message || '删除失败，请稍后重试');
            }
        })
        .catch(error => {
            console.error('删除好友时出错:', error);
            alert('删除好友失败，请稍后重试');
        });
    }
        
        // 查看资料
        function ckfr() {
            window.location.href = `userinfo.php?user=<?= urlencode($targetUserId) ?>`;
        }
        
        // 获取所有消息
        async function refreshMessages() {
            try {
                const response = await fetch('chat.php?fetch_messages=true&id=<?= urlencode($targetUserId) ?>');
                const messages = await response.json();
                renderMessages(messages);
                lastMessageId = messages.length > 0 ? messages[messages.length - 1].timestamp : 0;
                
                // 页面加载后滚动到底部
                setTimeout(scrollToBottom, 100);
            } catch (error) {
                console.error('获取消息失败:', error);
            }
        }
        
        // 仅获取新消息
        async function fetchNewMessages() {
            try {
                const response = await fetch('chat.php?fetch_messages=true&id=<?= urlencode($targetUserId) ?>');
                const messages = await response.json();
                
                // 找出新消息
                const newMessages = messages.filter(msg => 
                    new Date(msg.timestamp).getTime() > new Date(lastMessageId).getTime()
                );
                
                if (newMessages.length > 0) {
                    appendMessages(newMessages);
                    lastMessageId = newMessages[newMessages.length - 1].timestamp;
                    
                    // 如果用户已经在底部，自动滚动
                    if (isAtBottom) {
                        scrollToBottom();
                    }
                }
            } catch (error) {
                console.error('获取新消息失败:', error);
            }
        }
        
        // 渲染所有消息
        function renderMessages(messages) {
            const chatContainer = document.getElementById('chatContainer');
            chatContainer.innerHTML = '';
            
            messages.forEach(msg => {
                appendMessage(msg);
            });
            
            scrollToBottom();
        }
        
        // 追加新消息
        function appendMessages(messages) {
            messages.forEach(msg => {
                appendMessage(msg);
            });
        }
        
        // 渲染单条消息
        function appendMessage(msg) {
            const chatContainer = document.getElementById('chatContainer');
            const isSelf = msg.sender === "<?= $currentUser ?>";
            
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message');
            messageDiv.classList.add(isSelf ? 'sent' : 'received');
            
            if (msg.type === 'text') {
                messageDiv.innerHTML = `
                    <div>${msg.content}</div>
                    <div class="message-time">${formatMessageTime(msg.timestamp)}</div>
                `;
            } else if (msg.type === 'image') {
                messageDiv.innerHTML = `
                    <img src="${msg.content}" alt="图片消息" onclick="previewImage('${msg.content}')">
                    <div class="message-time">${formatMessageTime(msg.timestamp)}</div>
                `;
            }
            
            chatContainer.appendChild(messageDiv);
        }
        
        // 添加临时消息（发送中状态）
        function addPendingMessage(content, type = 'text') {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', 'sent', 'sending');
            const tempId = 'temp_' + Date.now();
            messageDiv.dataset.tempId = tempId;
            
            if (type === 'text') {
                messageDiv.innerHTML = `
                    <div>${content}</div>
                    <div class="message-time">${formatMessageTime(new Date())}</div>
                    <div class="message-status">发送中...</div>
                `;
            } else if (type === 'image') {
                messageDiv.innerHTML = `
                    <img src="${content}" alt="发送中的图片">
                    <div class="message-time">${formatMessageTime(new Date())}</div>
                    <div class="message-status">发送中...</div>
                `;
            }
            
            chatContainer.appendChild(messageDiv);
            scrollToBottom();
            
            return tempId;
        }
        
        // 更新消息状态
        function updateMessageStatus(tempId, status) {
            const messageDiv = document.querySelector(`.message[data-temp-id="${tempId}"]`);
            if (!messageDiv) return;
            
            // 移除发送中状态
            messageDiv.classList.remove('sending');
            
            if (status === 'success') {
                // 成功发送，移除临时标记
                messageDiv.removeAttribute('data-temp-id');
                // 移除状态指示器
                const statusDiv = messageDiv.querySelector('.message-status');
                if (statusDiv) {
                    statusDiv.remove();
                }
            } else if (status === 'error') {
                // 发送失败
                messageDiv.classList.add('failed');
                const statusDiv = messageDiv.querySelector('.message-status');
                if (statusDiv) {
                    statusDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> 发送失败';
                }
            }
        }
        
        // 发送文本消息
        async function sendMessage(event) {
            event.preventDefault();
            
            const messageInput = document.querySelector('.message-input');
            const message = messageInput.value.trim();
            
            if (!message) {
                alert('消息不能为空');
                return;
            }
            
            // 添加临时消息
            const tempId = addPendingMessage(message);
            
            try {
                const response = await fetch('chat.php?id=<?= urlencode($targetUserId) ?>', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `message=${encodeURIComponent(message)}`
                });
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 成功发送
                    updateMessageStatus(tempId, 'success');
                    
                    // 不再调用fetchNewMessages，避免重复消息
                    // 等待服务器推送新消息
                } else {
                    // 发送失败
                    updateMessageStatus(tempId, 'error');
                    alert(result.message);
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                updateMessageStatus(tempId, 'error');
                alert('消息发送失败，请检查网络连接');
            }
            
            // 清空输入框
            messageInput.value = '';
            messageInput.focus();
        }
        
        // 上传图片
        async function uploadImage(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 创建临时URL用于预览
            const tempUrl = URL.createObjectURL(file);
            
            // 添加临时消息
            const tempId = addPendingMessage(tempUrl, 'image');
            
            const formData = new FormData();
            formData.append('image', file);
            
            try {
                const response = await fetch('chat.php?id=<?= urlencode($targetUserId) ?>', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                if (result.status === 'success') {
                    // 成功发送
                    updateMessageStatus(tempId, 'success');
                    
                    // 不再调用fetchNewMessages，避免重复消息
                    // 等待服务器推送新消息
                } else {
                    // 发送失败
                    updateMessageStatus(tempId, 'error');
                    alert(result.message);
                }
            } catch (error) {
                console.error('上传图片失败:', error);
                updateMessageStatus(tempId, 'error');
                alert('图片上传失败，请检查网络连接');
            }
            
            // 清除临时URL
            setTimeout(() => URL.revokeObjectURL(tempUrl), 1000);
        }
        
        // 显示/隐藏表情面板
        function toggleEmojiPanel() {
            const emojiPanel = document.getElementById('emojiPanel');
            emojiPanel.classList.toggle('show');
        }
        
        // 添加表情
        function addEmoji(emoji) {
            const messageInput = document.querySelector('.message-input');
            messageInput.value += emoji;
            messageInput.focus();
        }
        
        // 触发文件选择
        function triggerFileInput() {
            document.getElementById('file-input').click();
        }
        
        // 预览图片
        function previewImage(imagePath) {
            const previewImage = document.getElementById('previewImage');
            const imageOverlay = document.getElementById('imageOverlay');
            
            previewImage.src = imagePath;
            imageOverlay.classList.add('show');
        }
        
        // 关闭预览
        function closePreview() {
            const imageOverlay = document.getElementById('imageOverlay');
            imageOverlay.classList.remove('show');
        }
        
        // 智能格式化消息时间
        function formatMessageTime(timestamp) {
            const now = new Date();
            const msgDate = new Date(timestamp);
            const diffInSeconds = Math.floor((now - msgDate) / 1000);
            
            // 今天内的消息
            if (isToday(msgDate)) {
                return formatTime(msgDate);
            }
            
            // 昨天的消息
            if (isYesterday(msgDate)) {
                return `昨天 ${formatTime(msgDate)}`;
            }
            
            // 一周内的消息
            if (diffInSeconds < 7 * 24 * 60 * 60) {
                return `${getWeekday(msgDate)} ${formatTime(msgDate)}`;
            }
            
            // 一年内的消息
            if (now.getFullYear() === msgDate.getFullYear()) {
                return `${msgDate.getMonth() + 1}月${msgDate.getDate()}日 ${formatTime(msgDate)}`;
            }
            
            // 超过一年的消息
            return `${msgDate.getFullYear()}年${msgDate.getMonth() + 1}月${msgDate.getDate()}日`;
        }
        
        // 检查是否是今天
        function isToday(date) {
            const today = new Date();
            return date.getDate() === today.getDate() &&
                   date.getMonth() === today.getMonth() &&
                   date.getFullYear() === today.getFullYear();
        }
        
        // 检查是否是昨天
        function isYesterday(date) {
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            return date.getDate() === yesterday.getDate() &&
                   date.getMonth() === yesterday.getMonth() &&
                   date.getFullYear() === yesterday.getFullYear();
        }
        
        // 获取星期几
        function getWeekday(date) {
            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            return weekdays[date.getDay()];
        }
        
        // 格式化时间 (HH:MM)
        function formatTime(date) {
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }
        
        // 点击外部关闭菜单和表情面板
        document.addEventListener('click', (e) => {
            const menu = document.querySelector('.dropdown-menu');
            const menuBtn = document.querySelector('.menu-btn');
            const emojiPanel = document.getElementById('emojiPanel');
            const emojiBtn = document.querySelector('.action-btn:nth-child(1)');
            
            if (menu.classList.contains('show') && !menu.contains(e.target) && !menuBtn.contains(e.target)) {
                menu.classList.remove('show');
            }
            
            if (emojiPanel.classList.contains('show') && !emojiPanel.contains(e.target) && !emojiBtn.contains(e.target)) {
                emojiPanel.classList.remove('show');
            }
        });
        function deleteFriend() {
    if (!confirm('确定要删除好友吗？此操作不可撤销！')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('delete_friend', 'true');
    
    fetch('delete_friend.php?id=<?= urlencode($targetUserId) ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        if (result.status === 'success') {
            alert(result.message);
            window.location.href = 'index.php';
        } else {
            alert(result.message || '删除失败，请稍后重试');
        }
    })
    .catch(error => {
        console.error('删除好友时出错:', error);
        alert('删除好友失败，请稍后重试');
    });
}
    </script>
</body>
</html>